/**
 * Copyright (c) 2016-2019 酷猪开源 All rights reserved.
 *
 * https://www.koopig.com
 *
 * 版权所有，侵权必究！
 */

package com.koo.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.koo.common.exception.RRException;
import com.koo.modules.sys.dao.SysRoleMenuDao;
import com.koo.modules.sys.entity.SysRoleMenuEntity;
import com.koo.modules.sys.service.SysRoleMenuService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


/**
 * 角色与菜单对应关系
 *
 * @author charlin
 */
@Service("sysRoleMenuService")
public class SysRoleMenuServiceImpl extends ServiceImpl<SysRoleMenuDao, SysRoleMenuEntity> implements SysRoleMenuService {



	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveOrUpdate(Long roleId, List<Long> menuIdList) {
		//先删除角色与菜单关系
		deleteBatch(new Long[]{roleId});

		if(menuIdList.size() == 0){
			return ;
		}

		//保存角色与菜单关系
		for(Long menuId : menuIdList){
			SysRoleMenuEntity sysRoleMenuEntity = new SysRoleMenuEntity();
			sysRoleMenuEntity.setMenuId(menuId);
			sysRoleMenuEntity.setRoleId(roleId);

			this.save(sysRoleMenuEntity);
		}
	}

	@Override
	public List<Long> queryMenuIdList(Long roleId) {
		return baseMapper.queryMenuIdList(roleId);
	}

	@Override
	public int deleteBatch(Long[] roleIds){
		return baseMapper.deleteBatch(roleIds);
	}

	@Override
	public Integer deleteByRoleId(Long roleId) {
		if(roleId != null){
			LambdaQueryWrapper<SysRoleMenuEntity> wrapper = new LambdaQueryWrapper();
			wrapper.eq(roleId != null, SysRoleMenuEntity::getRoleId, roleId );
			return baseMapper.delete(wrapper);
		}
		return null;
	}

    @Override
    public List<Long> getMenuIdList(Long roleId) {
        return baseMapper.queryMenuIdList(roleId);
    }

	@Override
	public Boolean updateRights(Long roleId, Long[] ids) {
		if(roleId == null) {
			throw new RRException("请选择角色！");
		}
		if(ids == null || ids.length == 0) {
			throw new RRException("请选择权限！");
		}
		//删除所有原来的权限，
		LambdaQueryWrapper<SysRoleMenuEntity> wrapper = new LambdaQueryWrapper();
		wrapper.eq(roleId != null, SysRoleMenuEntity::getRoleId, roleId);
		baseMapper.delete(wrapper);
		//添加新的权限
		LambdaUpdateWrapper<SysRoleMenuEntity> updateWrapper = new LambdaUpdateWrapper();
		updateWrapper.eq(roleId != null, SysRoleMenuEntity::getRoleId, roleId);

		List<SysRoleMenuEntity> list = new ArrayList<SysRoleMenuEntity>();
		for(Long menuId : ids){
			SysRoleMenuEntity sysRoleMenuEntity = new SysRoleMenuEntity();
			sysRoleMenuEntity.setRoleId(roleId);
			sysRoleMenuEntity.setMenuId(menuId);
			list.add(sysRoleMenuEntity);
		}
		return this.saveBatch(list);
	}

}
